package com.voicenews.pushnews;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;
import com.voicenews.dao.ConnectionFactory;
import com.voicenews.model.Article;
import com.voicenews.model.DAO;

public class ArticlesToUsersSender {
	private static final String SENDER_ID = "AIzaSyD06tlwXt_JvaRx-4ojadBu2OW_cvZBj0Y";
	private Connection conn = null;
	private Statement statement = null;

	private Connection getConnection() throws SQLException {
		Connection conn;
		conn = ConnectionFactory.getInstance().getConnection();
		return conn;
	}

	public void sendArticlesToUser(HashMap<Long, List<Article>> idTopicA) {
		try {
			conn = this.getConnection();
			statement = conn.createStatement();
			ResultSet resultSet = null;
			Sender sender = new Sender(SENDER_ID);
			for (Iterator<Entry<Long, List<Article>>> iterator = idTopicA
					.entrySet().iterator(); iterator.hasNext();) {
				List<String> androidTargets = new ArrayList<String>();
				Entry<Long, List<Article>> pair = (Entry<Long, List<Article>>) iterator
						.next();
				List<Article> articlesList = pair.getValue();
				String queString = "select id_gcm from user where id_topic_registration = "
						+ pair.getKey();
				System.out.println("id : " + pair.getKey() + " size : "
						+ pair.getValue().size());
				resultSet = statement.executeQuery(queString);
				while (resultSet.next()) {
					androidTargets.add(resultSet.getString("id_gcm"));
				}

				if (androidTargets.size() != 0) {
					System.out.println(androidTargets.size());
					JSONArray array = new JSONArray();
					JSONObject messageJson = new JSONObject();
					messageJson.put("article", array);
					for (int i = 0; i < articlesList.size(); i++) {
						Article article = articlesList.get(i);
						JSONObject tmp = new JSONObject();
						tmp.put("title", article.getTitle());
						System.out.println(article.getTitle());
						tmp.put("url", article.getUrl().toString());
						tmp.put("articleId", article.getArticleId());
						array.add(tmp);
					}

					Message message = new Message.Builder()

							// If multiple messages are sent using the same
							// .collapseKey()
							// the android target device, if it was offline
							// during
							// earlier
							// message
							// transmissions, will only receive the latest
							// message for
							// that
							// key when
							// it goes back on-line.
							.collapseKey("GCM_Message").timeToLive(30)
							// .delayWhileIdle(true)
							.addData("message", messageJson.toJSONString())
							.build();

					try {
						// use this for multicast messages. The second parameter
						// of sender.send() will need to be an array of register
						// ids.
						MulticastResult result = sender.send(message,
								androidTargets, 1);

						if (result.getResults() != null) {
							int canonicalRegId = result.getCanonicalIds();
							if (canonicalRegId != 0) {
								System.out.println("success");
							}
						} else {
							int error = result.getFailure();
							System.out.println("Broadcast failure: " + error);
						}

					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
				}
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (statement != null) {
				try {
					statement.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

}
